package com.leon.lifeenginespace.thread;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description:多线程实战
 * @author: WT
 * @date: 2024/4/1 23:47
 * @Version 1.0
 **/
public class Demo {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = new ThreadPoolExecutor(
                1, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new MyThreadFactory() {
        }
        );
        Future<String> submit = es.submit(new MyCallable());
        try {
            System.out.println(submit.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        // 启动新线程
        System.out.println("start main thread!");
        //线程状态
        //New       新建状态
        //Runnable  运行中
        //Blocked   阻塞挂起
        //Waiting   等待
        //Timed Waiting 睡眠
        //Terminated    终止  终止原因 ： return/throw Exception/stop
        MyThread t = new MyThread();
        //Daemon Thread 要在start之前
        //子线程的创建不是父子关系通过共享变量判断存活
        //while (t.isAlive())
        t.setDaemon(true);
        t.start();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //优先级
        t.setPriority(1);
        //中断线程   interrupt/设置标志位
        // 标志位置为fals
        t.running = false;
        t.interrupt();
        //一个线程还可以等待另一个线程直到其运行结束 join
        t.join(1000);
        for (int i = 0; i < 10000; i++) {
            synchronized (Counter.lock) {
                Counter.count += 1;
            }
        }
        //保证前面的线程都执行完
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println("main end...");
        //可重入锁 sync 死锁  volatile是保证可见性  sync是保证原子性
        //什么不是原子性多线程场景下要保证原子性   赋值操作


    }
    static class MyThreadFactory implements ThreadFactory{

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "MyThread"+ Thread.currentThread().getId());
        }
    }
}


class MyThread extends Thread {

    //volatile 没有原子性 但有可见性
    //每次访问变量时，总是获取主内存的最新值；
    //每次修改变量后，立刻回写到主内存；
    //但是volatile可以保证有序性。程序执行到volatile变量的读操作或者写操作时，在其前面的语句中，更改操作肯定已经完成，且结果已经对后面的操作可见，在其后面的操作肯定还没有进行。
    public volatile boolean running = true;

    @Override
    public void run() {
        System.out.println("start t thread!");
        int counter = 0;


        while (running) {
            System.out.println(counter + " hello!");
        }
        //不要显示创建线程
//        Thread r = new Thread(new MyRunnable());
        Thread r = new MyRunnable();
        r.start();
        try {
            // 等待r线程结束
            r.join();
        } catch (InterruptedException e) {
            System.out.println("interrupted!");
        }
        r.interrupt();

        try {
            Thread.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end t thread!");
    }

    /**
     * cas 的含义是compare and set
     * @param counter
     * @return
     */
    public int cas(AtomicInteger counter ){
        int prev, next;
        do {
            prev = counter.get();
            next = prev + 1;
        } while (!counter.compareAndSet(prev, next));
        return next;
    }
}

class MyRunnable extends Thread {
    @Override
    public void run() {
        System.out.println("start r thread!");
        int counter = 0;
        while (!isInterrupted()) {
            counter++;
            System.out.println(counter + " hello!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("interrupted!");
                break;
            }
        }
        System.out.println("end r thread!");
    }
}
class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "null";
    }
}


class Counter {
    //读写锁
    private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
    private final Lock rlock = rwlock.readLock();
    private final Lock wlock = rwlock.writeLock();
    public static final Object lock = new Object();
    public static int count = 0;
}


